package com.weiqiao.mall.service.impl;

import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.mall.domain.AccountDetailEntity;
import com.weiqiao.mall.domain.AppUserEntity;
import com.weiqiao.mall.domain.ReceiptEntity;
import com.weiqiao.mall.repository.IAccountDetaiRepository;
import com.weiqiao.mall.repository.IAppUserRepository;
import com.weiqiao.mall.repository.IReceiptRepository;
import com.weiqiao.mall.service.IReceiptService;
import com.weiqiao.mall.service.vo.ReceiptVO;
import com.weiqiao.utils.DateUtil;
import com.weiqiao.utils.DateUtils;
import com.weiqiao.utils.PageUtil;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service("ReceiptServiceImpl")
public class ReceiptServiceImpl implements IReceiptService {

    @Autowired
    private IReceiptRepository receiptRepository;

    @Autowired
    private IAccountDetaiRepository accountDetaiRepository;

    @Autowired
    private IAppUserRepository appUserRepository;

    @Override
    public Map findReceiptList(ReceiptVO vo) {
        //组装查询条件
        Document doc = this.setDocument(vo);
        // 按申请时间倒序排序
        Bson sort = Filters.eq("apply_date", -1);
        // 分页参数设置
        Pageable pageable = PageRequest.of(vo.getPage(), vo.getSize());
        List<ReceiptEntity> receiptList = new ArrayList();
        List<String> list = receiptRepository.findReceipt(vo.getCompany_id(), doc, sort, pageable);
        if (!StringUtil.isBlank(list)) {
            for (String str : list) {
                ReceiptEntity entity = new Gson().fromJson(str, ReceiptEntity.class);
                if (!StringUtil.isBlank(entity.getPhone())) {
                    entity.setPhone(entity.getPhone().replaceAll("(\\d{3})\\d{4}", "$1****"));
                }
                receiptList.add(entity);
            }
        }
        // 获取数量
        int size = this.findRecepitSize(vo.getCompany_id(), doc);
        return PageUtil.toPage(receiptList, size);
    }

    @Override
    public ReceiptEntity queryOneReceiptById(int company_id, String receipt_no) {
        Document document = new Document();
        document.append("company_id", company_id);
        document.append("receipt_no", receipt_no);
        String str = receiptRepository.queryOneReceiptById(company_id, document);
        if (!StringUtil.isBlank(str)) {
            ReceiptEntity receiptEntity = new Gson().fromJson(str, ReceiptEntity.class);
            return receiptEntity;
        }
        return new ReceiptEntity();
    }

    @Override
    public boolean updateRecepits(int company_id, Bson filter, Document doc) {
        return receiptRepository.updateRecepits(company_id, filter, doc);
    }

    @Override
    public List<ReceiptEntity> queryOneReceiptByIds(int company_id, List<String> receipt_nos) {
        Bson filter = Filters.in("receipt_no", receipt_nos);
        List<String> list = receiptRepository.queryOneReceiptByIds(company_id, filter);
        List<ReceiptEntity> receiptEntityList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (String s : list) {
                receiptEntityList.add(new Gson().fromJson(s, ReceiptEntity.class));
            }
        }
        return receiptEntityList;
    }

    @Override
    public boolean updateDealStatusById(ReceiptVO vo) {
        // 数据校验
        if (StringUtil.isBlank(vo.getReceipt_no())) {
            return false;
        }
        // 公司id
        Integer company_id = vo.getCompany_id();
        List<String> receipt_nos = vo.getReceipt_no();
        Document upDoc = new Document("receipt_no", new Document("$in", receipt_nos));
        // 判断是那个页面进行的操作
        if ("0".equals(vo.getFlag())) { // 提现申请
            return this.updateRecepits(company_id,
                    upDoc,
                    new Document("status", 2)
            );
        } else { // 提现打款
            List<ReceiptEntity> receips = this.queryOneReceiptByIds(company_id, receipt_nos);
            receips.forEach(entity -> {
                int user_id = entity.getUser_id();
                String receipt_no1 = entity.getReceipt_no();
                Document document = new Document()
                        .append("user_id", user_id)
                        .append("receipt_no", receipt_no1);
                String accountDetail = accountDetaiRepository.findOneAccountDetail(company_id, document);
                // 更新收支流水明细
                if (!StringUtil.isBlank(accountDetail)) {
                    AccountDetailEntity oneAccountDetail = new Gson().fromJson(accountDetail, AccountDetailEntity.class);
                    oneAccountDetail.setResult_type(1);
                    oneAccountDetail.setDeal_time(String.valueOf(System.currentTimeMillis()));
                    accountDetaiRepository.updateDetail(Document.parse(new Gson().toJson(oneAccountDetail)),
                            document, company_id);
                }
            });
            return this.updateRecepits(
                    company_id,
                    upDoc,
                    new Document()
                            .append("deal_date", DateUtils.currentTimeMillis())
                            .append("status", 3)
            );
        }
    }

    @Override
    public boolean rebutRecepit(ReceiptVO vo) {
        Integer company_id = vo.getCompany_id();
        List<String> receipt_nos = vo.getReceipt_no();
        // 查询提现信息
        List<ReceiptEntity> receips = this.queryOneReceiptByIds(company_id, receipt_nos);
        if (receips.size() == 0) {
            return false;
        }
        for (ReceiptEntity entity : receips) {
            Document document = new Document("user_id", entity.getUser_id());
            // 查询用户信息
            String appUser = appUserRepository.getAppUserByFilter(document, company_id);
            if (StringUtil.isBlank(appUser)) {
                continue;
            }
            // 更改状态为已驳回
            entity.setStatus(1);
            // 修改提现实体
            boolean receipt_flag = receiptRepository.updateOne(
                    company_id,
                    new Document("receipt_no", entity.getReceipt_no()),
                    new Gson().toJson(entity)
            );
            if (!receipt_flag) {
                continue;
            }
            // 修改该条提现流水的结算状态
            Document accountDocument = new Document()
                    .append("receipt_no", entity.getReceipt_no())
                    .append("happen_proceed", 1);
            Document accountUpdate = new Document()
                    .append("deal_time", String.valueOf(System.currentTimeMillis()))
                    .append("result_type", 1);
            accountDetaiRepository.updateDetail(accountUpdate, accountDocument, company_id);

            AppUserEntity userEntity = new Gson().fromJson(appUser, AppUserEntity.class);
            // 驳回返还金额
            Document updateUser = new Document("score", userEntity.getScore() + entity.getAdvance_pay());
            boolean flag = appUserRepository.updateAppUser(updateUser, document, company_id);
            if (flag) {
                // 组装流水
                AccountDetailEntity detailEntity = new AccountDetailEntity();
                detailEntity.setAccount_no(String.valueOf(System.currentTimeMillis()));
                // 金额
                detailEntity.setAccount_money(entity.getAdvance_pay());
                detailEntity.setPhone(userEntity.getPhone());
                // 佣金驳回
                detailEntity.setHappen_proceed(8);
                detailEntity.setReceipt_no(entity.getReceipt_no());
                // 收入
                detailEntity.setAccount_state(0);
                detailEntity.setUser_id(userEntity.getUser_id());
                detailEntity.setName(userEntity.getNickname());
                detailEntity.setIcon_url(userEntity.getIcon_url());
                detailEntity.setRemark(vo.getRemark());
                detailEntity.setResult_type(1);
                detailEntity.setMember_type(userEntity.getMember_type());
                detailEntity.setDelete_flag(0);
                detailEntity.setCompany_id(company_id);
                detailEntity.setCreat_time(String.valueOf(System.currentTimeMillis()));
                // 生成流水
                accountDetaiRepository.insertOne(company_id, new Gson().toJson(detailEntity));
            }
        }
        return true;
    }

    @Override
    public int findRecepitSize(int company_id, Bson filter) {
        return receiptRepository.findAll(company_id, filter).size();
    }

    private Document setDocument(ReceiptVO vo) {
        Document doc = new Document()
                .append("delete_flag", 0) // 未删除的
                .append("company_id", vo.getCompany_id());// 公司id

        // 用户编号
        if (StringUtil.isInteger(vo.getUser_id())) {
            doc.append("user_id", vo.getUser_id());
        }
        // 用户姓名
        if (!StringUtil.isBlank(vo.getUser_name())) {
            doc.append("user_name", new Document("$regex", vo.getUser_name()));
        }
        // 手机号
        if (!StringUtil.isBlank(vo.getPhone())) {
            doc.append("phone", new Document("$regex", vo.getPhone()));
        }
        // 申请时间
        if (!StringUtil.isBlank(vo.getApply_date())) {
            String apply_date1 = DateUtil.stringToTimestamp(vo.getApply_date().split("~")[0]);
            String apply_date2 = DateUtil.stringToTimestamp(vo.getApply_date().split("~")[1]);
            doc.append("apply_date", new Document("$gt", apply_date1));
            doc.append("apply_date", new Document("$lt", apply_date2));
        }
        /**
         * 结合flg一起判断查询条件
         * 处理状态 0：未处理 1: 已驳回  2：待打款  3：已打款
         */
        if ("0".equals(vo.getFlag())) { // 提现审核
            if (StringUtil.isInteger(vo.getStatus())) {
                int status = vo.getStatus();
                if (status == 0) { // 未处理
                    doc.append("status", status);
                } else { // 已处理
                    doc.append("status", new Document("$in", Arrays.asList(1, 2)));
                }
            } else {
                doc.append("status", new Document("$ne", 3));
            }
        } else { // 提现打款
            if (StringUtil.isInteger(vo.getStatus())) {
                int status = vo.getStatus();
                doc.append("status", status == 0 ? 2 : 3);
            } else {
                doc.append("status", new Document("$in", Arrays.asList(2, 3)));
            }
        }
        // 提现类型
        if (StringUtil.isInteger(vo.getPayment())) {
            doc.append("payment", vo.getPayment());
        }
        // 等级角色
        if (StringUtil.isInteger(vo.getMember_type())) {
            doc.append("member_type", vo.getMember_type());
        }
        return doc;
    }
}
